package com.vincent.template.config;

import com.vincent.template.service.security.impl.UserDetailsServiceImpl;
import com.vincent.template.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @Author Vincent Wang
 * @Date 2020/10/27 19:01
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new PasswordEncoder() {
            @Override
            public String encode(CharSequence password) {
                return Md5Util.encode(password);
            }
            @Override
            public boolean matches(CharSequence password, String encodedStr) {
                return Md5Util.match(password, encodedStr);
            }
        };
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .antMatchers("/", "/index").permitAll()
                .antMatchers("/login").permitAll()
                .antMatchers("/**")
                .access("@userAccessServiceImpl.isAccessible(request, authentication)")
                .anyRequest().authenticated()
                .and().formLogin().loginPage("/login");

        http.csrf().disable();
    }
}
